<template>
  <div>
     <!-- 面包屑 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
        <el-alert title="添加商品信息!" type="info" :closable="false" show-icon></el-alert>
        <!-- 步骤条 -->
        <el-steps :active="activeIndex - 0" finish-status="success" align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>
        <!-- tabs -->
        <el-form :model="goodsForm" :rules="rules" ref="formRef" label-width="100px" label-position="top"	>
          <el-tabs :tab-position="tabPosition" stretch v-model="activeIndex" 
          :before-leave="beforeTabsLeval" @tab-click="sortGoods">
              <el-tab-pane label="基本信息" name="0">
                <el-form-item label="商品名称" prop="goods_name">
                  <el-input v-model="goodsForm.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" prop="goods_price">
                  <el-input type="number" v-model="goodsForm.goods_price"></el-input>
                </el-form-item>
                <el-form-item label="商品重量" prop="goods_weight">
                  <el-input type="number" v-model="goodsForm.goods_weight"></el-input>
                </el-form-item>
                <el-form-item label="商品数量" prop="goods_number">
                  <el-input type="number" v-model="goodsForm.goods_number"></el-input>
                </el-form-item>
                <el-form-item label="商品分类" prop="goods_cat">
                  <!-- 多级选择器 -->
                  <el-cascader v-model="goodsForm.goods_cat" clearable :options="goodsList" :props="prop"
                    @change="changeSelect">
                  </el-cascader>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品参数" name="1">
                <el-form-item :label="item.attr_name" v-for="item in manyList" :key="item.attr_id">
                  <!-- 多选框组 -->
                  <el-checkbox-group v-model="item.attr_vals">
                    <el-checkbox border :label="attr" v-for="(attr,index) in item.attr_vals" :key="index"></el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品属性" name="2">
                <el-form-item :label="item.attr_name" v-for="item in onlyList" :key="item.attr_id">
                  <el-input v-model="item.attr_vals"></el-input>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品图片" name="3">
                <el-upload
                  class="upload-demo"
                  action="http://127.0.0.1:8888/api/private/v1/upload"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :file-list="fileList"
                  :headers="headerObj"
                  list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-tab-pane>
              <el-tab-pane label="商品内容" name="4">
                <quill-editor v-model="goodsForm.goods_introduce">
                </quill-editor>
                <el-button type="primary" class="el_btn" @click="addGoods">确定添加</el-button>
              </el-tab-pane>
          </el-tabs>
        </el-form>
    </el-card>
    <!-- 此对话框是用来展示预览图片的 :before-close="dialogBeforeClose"-->
    <el-dialog title="预览图片" :visible.sync="dialogVisible" width="width">
      <div>
        <img :src="PreviewUrl" alt="" width="100%">
      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
    name:'add',
    data(){
        return{
          tabPosition: 'left',
          activeIndex: 0,
          // 收集表单的数据
          goodsForm:{
            goods_name:'',
            goods_price:'',
            goods_cat:[],// 收集多级选择器选中的value
            goods_number:'',
            goods_weight:'',
            goods_introduce:'',//编辑内容
            pics:[],//收集照片
            attrs: []
          },
          // 表单验证规则
          rules: {
            goods_name: [
              { required: true, message: '请输入商品名称', trigger: 'blur' },
            ],
            goods_price: [
              { required: true, message: '请输入商品价格', trigger: 'blur' },
            ],
            goods_cat: [
              { required: true, message: '请输入商品分类', trigger: 'blur' },
            ],
            goods_number: [
              { required: true, message: '请输入商品数量', trigger: 'blur' },
            ],
            goods_weight: [
              { required: true, message: '请输入商品重量', trigger: 'blur' },
            ],
          },
          // 多级选择器的展示数据的配置
          prop:{ 
              expandTrigger: 'hover',
              value: 'cat_id',
              label:'cat_name', 
              children: 'children'
          },
          // 展示到多级选择器的数据
          goodsList:[],
          // 储存动态参数
          manyList: [],
          // 储存静态参数
          onlyList:[],
          // 图片上传的请求头
          headerObj:{
            Authorization:window.sessionStorage.getItem('token')
          },
          // 收集上传图片
          fileList:[],
          // 收集预览图片的地址
          PreviewUrl: '',
          // 对话框显隐
          dialogVisible:false
        }
    },
    methods:{
      // 获取要展示到多级选择器的数据
       async getGoodsList(){
        let {data:result} = await this.$API.get('categories')
        if(result.meta.status !== 200){
          return this.$message.error('请求数据失败')
        }
        this.goodsList = result.data
       },
      //  多级选择器选中改变时
      changeSelect(arr){
        if(arr.length !=3){
          this.goodsForm.goods_cat = []
          return
        } 
        this.goodsForm.goods_cat = arr
      },
      // tabs切换前的回调
      beforeTabsLeval(active,oldActive){
        if(this.goodsForm.goods_cat.length != 3&& oldActive == '0') {
          this.$message.error('请选择三级分类')
          return false
        }
      },
      // tabs被选中的回调
      async sortGoods(){
        let id = this.goodsForm.goods_cat[2]
        // 当是商品参数时
        if(this.activeIndex == 1){
          // many是 获取动态数据
          let {data:result} = await this.$API.get(`categories/${id}/attributes`,{params:{sel:['many']}})
         if(result.meta.status !== 200){
          return this.$message.error('请求数据失败')
         }
         result.data.forEach(item => {
          // 将来要渲染为复选框的内容
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
         })
         this.manyList = result.data
        }else if(this.activeIndex == 2){
          let {data:result} = await this.$API.get(`categories/${id}/attributes`,{params:{sel:['only']}})
          if(result.meta.status !== 200){
            return this.$message.error('请求数据失败')
          }
          this.onlyList = result.data
        }
        
      },
      // 删除图片
      handleRemove(file, fileList) {
        // 移除收集照片地址的数组
        let filePath = file.response.data.tmp_path
        let index = this.goodsForm.pics.findIndex(item => item.pics == filePath)
        this.goodsForm.pics.splice(index,1)
      },
      // 预览图片
      handlePreview(file) {
        this.PreviewUrl = file.response.data.url
        this.dialogVisible = true
      },
      // 图片上传成功
      handleSuccess(response, file, fileList){
        let obj = {pic:response.data.tmp_path}
        this.goodsForm.pics.push(obj)
      },
      // 确定添加商品
      addGoods(){
        this.$refs.formRef.validate(async (vali) =>{
          if(!vali) return this.$message.error('请写必要的表单项')
          // 处理选择器选中的数据和动态、静态参数
          const form = _.cloneDeep(this.goodsForm)
          form.goods_cat = form.goods_cat.join(',')
          // 处理动态、静态参数
          this.manyList.forEach(item =>{
            let newInfo = {
              attr_id : item.attr_id,
              attr_value : item.attr_vals.join(' ')
            }
            this.goodsForm.attrs.push(newInfo)
          })
          this.onlyList.forEach(item =>{
            let newInfo = {
              attr_id: item.attr_id,
              attr_value:item.attr_vals
            }
            this.goodsForm.attrs.push(newInfo)
          })
          form.attrs = this.goodsForm.attrs
          // 发起添加请求
          let {data:result} = await this.$API.post('goods',form)
          if(result.meta.status !== 201)return this.$message.error('添加商品失败')
          this.$message.success('添加商品成功')
          // 跳转到goods路由
          this.$router.push('/goods')
        })
      }
    },
    mounted(){
      this.getGoodsList()
    }
}
</script>

<style>
.el-steps{
    margin: 20px 0;
}
.el-cascader-panel{
  height: 260px;
}
.ql-container{
  height: 200px;
}
.el_btn{
  margin: 20px 0;
}
</style>